/**
 * Notes: 公共跨项目控制器
 * Date: 2025-05-01
 */

const BaseController = require('../../oa/controller/base_controller.js');
const { EventBusService, EVENT_TYPES } = require('../service/event_bus_service.js');
const AppError = require('../../../framework/core/app_error.js');

/**
 * 公共跨项目控制器
 */
class CrossController extends BaseController {
  constructor() {
    super();
    this.eventBus = new EventBusService();
  }

  /**
   * 发布事件
   */
  async publishEvent() {
    // 获取身份验证结果
    const authResult = this._event._authResult;
    if (!authResult || !authResult.auth) {
      return this.error('未通过身份验证');
    }

    // 获取请求参数
    const eventType = this.getParameter('type');
    const eventData = this.getParameter('data');

    // 参数校验
    if (!eventType) {
      return this.error('事件类型不能为空');
    }
    if (!eventData) {
      return this.error('事件数据不能为空');
    }
    if (!EVENT_TYPES[eventType]) {
      return this.error(`未知的事件类型: ${eventType}`);
    }

    try {
      // 添加发布者信息
      const enrichedData = {
        ...eventData,
        _publisher: {
          id: authResult.id,
          name: authResult.name,
          department: authResult.department
        },
        _publishTime: Date.now()
      };

      // 发布事件
      const eventId = await this.eventBus.publish(eventType, enrichedData);

      // 返回结果
      return this.success({
        id: eventId,
        type: eventType,
        status: 'published'
      });
    } catch (error) {
      console.error(`[CROSS_CONTROLLER] 发布事件失败: ${error.message}`);
      return this.error(`发布事件失败: ${error.message}`);
    }
  }

  /**
   * 处理待处理事件
   */
  async processPendingEvents() {
    // 获取身份验证结果
    const authResult = this._event._authResult;
    if (!authResult || !authResult.auth || authResult.level < 2) {
      return this.error('需要管理员权限');
    }

    try {
      // 处理待处理事件
      const result = await this.eventBus.processPendingEvents();

      // 记录处理者信息
      result.processedBy = {
        id: authResult.id,
        name: authResult.name,
        time: new Date().toISOString()
      };

      // 返回结果
      return this.success(result);
    } catch (error) {
      console.error(`[CROSS_CONTROLLER] 处理事件失败: ${error.message}`);
      return this.error(`处理事件失败: ${error.message}`);
    }
  }

  /**
   * 健康检查
   */
  async healthCheck() {
    return this.success({
      service: 'Cross Service',
      status: 'ok',
      timestamp: new Date().toISOString()
    });
  }
}

module.exports = CrossController; 